﻿<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Connexion extends CI_Controller
{
    public function index()
    {
        if($this->session->userdata('connecte'))
		{
			redirect('accueil');
		}
		
        $this->form_validation->set_rules('courriel', 'Courriel', 'required|trim|valid_email');
		$this->form_validation->set_rules('mdp', 'Mot de passe', 'required|trim');

		if($this->form_validation->run() == FALSE)
		{
			load_template('connexion');
		}
		else
		{
		    $email = $this->input->post('courriel');
		    $password = $this->input->post('mdp');
			$this->load->model('connexion_model');
			$identifiant = $this->connexion_model->check($email, $password);
			switch($identifiant)
			{
			    case -1:
			        //Password does not match.
			        $this->form_validation->set_message('Password does not match.');
			        load_template('connexion');
			        break;
			    case 0:
			        //No user with this email.
			        $this->form_validation->set_message('No user with this email.');
			        load_template('connexion');
			        break;
			    default:
			        $data = $this->connexion_model->get_user_informations($identifiant);
					$this->session->set_userdata('connecte', true);
			        $this->session->set_userdata('identifiant', $identifiant);
			        $this->session->set_userdata('nom', $data->nom);
			        $this->session->set_userdata('prenom', $data->prenom);
			        $this->session->set_userdata('courriel', $data->courriel);
			        redirect('accueil');
			        break;
			}
		}
    }
}